package com.aliengen.thingple.thingple.api;

import android.os.AsyncTask;

import com.aliengen.thingple.thingple.service.HandsetApplication;
import com.aliengen.thingple.thingple.tag.CylinderTag;
import com.aliengen.thingple.thingple.tag.Tag;

import java.util.ArrayList;
import java.util.Iterator;

/**
 * This class is part of the Thingple mobile application for the CMC168 Handheld reader.
 *
 * Copyright AlienGen Limited 2016. All rights reserved.
 *
 * @author Timothé Mermet-Buffet <tim@aliengen.com>
 */
public class AsyncTagUpdate extends AsyncTask<ArrayList<Tag>, Integer, Integer> {

    protected OnExecuteListener mExecuteListener = null;
    protected HandsetApplication mApplication;

    public interface OnExecuteListener {
        public void onPostExecute();
        public void onProgressUpdate();
        public void onMessage(String message);
    }

    @Override
    protected Integer doInBackground(ArrayList<Tag>... list) {
        int length = list.length;
        int total = 0;
        for(int i = 0; i < length; i++) {
            Iterator<Tag> iter = list[i].iterator();

            while (iter.hasNext()) {
                Tag t = iter.next();
                if (mApplication.mService.api.syncCylinderTag(t)) {
                    total++;
                } else {
                    if (mExecuteListener != null) {
                       mExecuteListener.onMessage(mApplication.mService.api.getLastErrors());
                    }
                }
            }
        }

        return total;
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        if(mExecuteListener != null)
        {
            mExecuteListener.onProgressUpdate();
        }
    }

    @Override
    protected void onPostExecute(Integer o) {
        super.onPostExecute(o);

        if(mExecuteListener != null)
        {
            mExecuteListener.onPostExecute();
        }
    }

    public void setOnExecuteListener(OnExecuteListener listener)
    {
        this.mExecuteListener = listener;
    }

    public void setApplication(HandsetApplication mApplication)
    {
        this.mApplication = mApplication;
    }
}
